package com.projects.candientu.utils;

import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

public class DataProvider {
	public List<RowData> loadAllData(Context vCtx) {
		List<RowData> myData = null;
		try {
			// Send GET request to <service>/GetPlates
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet request = new HttpGet(new URI(Utils.SERVICE_URI
					+ "/DuLieu_SelectAll"));
			request.setHeader("Accept", "application/json");
			request.setHeader("Content-type", "application/json");

			HttpResponse response = httpClient.execute(request);
			HttpEntity responseEntity = response.getEntity();
			// Read response data into buffer
			String result = Utils.getResponse(responseEntity);
			Log.i("loadAllData", "Response: " + result);

			if (result != "") {
				// Init array objects
				JSONArray arrData = new JSONArray(result);
				myData = new ArrayList<RowData>();

				// Loop for all reveived objects
				for (int i = 0; i < arrData.length(); i++) {
					JSONObject data = (JSONObject) arrData.get(i);
					// Update value - key for intent
					addItem(myData, i + 1, data.getString("ID"),
							data.getString("IDGio"),
							data.getString("KhoiLuong"),
							data.getString("ThoiDiemDo"));
				}
				
				// Sort row items by descreasing by ThoiDiemDo
				Collections.sort(myData, Utils.sDisplayNameComparator);
			}
		} catch (Exception e) {
			Log.e("loadAllData", "Error on loadAllData: " + e.toString());
		}
		return myData;
	}

	private void addItem(List<RowData> data, int stt, String id, String idgio,
			String khoiluong, String thoidiemdo) {
		RowData temp = new RowData(stt, id, idgio, khoiluong, thoidiemdo);
		data.add(temp);
	}
}
